import { LinkList } from "./01_单向链表_重构";

export class CircularLinkedList<T> extends LinkList<T> {
  //重写append方法
  append(value: T): void {
    super.append(value);
    //拿到最后一个节点next指向第一个节点
    this.tail!.next = this.head;
  }

  //重写insert方法
  insert(value: T, position: number): boolean {
    const isSuccess = super.insert(value, position);

    if (isSuccess && (position === this.length - 1 || position === 0)) {
      //尾部插入 or 尾部插入
      this.tail!.next = this.head;
    }
    return isSuccess;
  }

  removeAt(position: number): T | null {
    const value = super.removeAt(position);

    //首尾相连  单向链表中只是加入了尾指针
    if (value && this.tail && (position === 0 || position === this.length)) {
      this.tail.next = this.head;
    }

    return value;
  }
}

const circularLinkedList = new CircularLinkedList();
circularLinkedList.append("a");
circularLinkedList.append("b");
circularLinkedList.append("c");
circularLinkedList.append("d");

circularLinkedList.insert("abc", 0);
circularLinkedList.insert("def", 5);

circularLinkedList.removeAt(0);
circularLinkedList.traverse();
circularLinkedList.removeAt(4);
circularLinkedList.traverse();
